package com.ifuncat.gulimall.product.exception;
import com.ifuncat.gulimall.common.exception.BizCodeEnum;
import com.ifuncat.gulimall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 统一异常处理
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.ifuncat.gulimall.product.controller")
public class ExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("数据校验异常: {}, 异常类型: {}", e.getMessage(), e.getClass());
        Map<String, String> map = new HashMap<>();
        //1.获取校验错误结果
        e.getBindingResult().getFieldErrors().forEach(i -> {
            String message = i.getDefaultMessage();//错误提示
            String field = i.getField(); //错误属性名
            map.put(field, message);
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION).put("data", map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleUnknownException(Throwable throwable) {
        log.error("未知异常: ", throwable);
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION);
    }
}
